﻿/*
 *  date: 2021-12-08
 *  author: Jn-chen
 *  cn: 事件控制器
 *  en: todo:
 */


using System.Collections.Generic;



namespace UBJ.EventKit
{

    public class EventController : IEventCtrl
    {
        /// <summary>
        /// 获取一个事件控制器
        /// </summary>
        /// <param name="name"> 事件控制器名字 </param>
        /// <returns> 事件控制器对象 </returns>
        public static EventController GetEventCtrl(string name)
        {
            return EventManager.Ins.GetEventCtrl(name);
        }

        public string Name { get; private set; }

        /// <summary>
        /// 通知事件
        /// </summary>
        /// <param name="name"> 事件名 </param>
        /// <param name="args"> 事件参数 </param>
        public void NotifyEvent(string name, params object[] args)
        {
            if (!mAllEvents.ContainsKey(name)) return;

            for(int i = 0; i < mAllEvents[name].Count; i++)
            {
                var myEvent = mAllEvents[name][i];
                myEvent?.Invoke(args);
            }
        }

        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="name"> 事件名 </param>
        /// <param name="msgHandler"> 事件 </param>
        public void RegistEvent(string name, MessageHandler msgHandler)
        {
            if (!mAllEvents.ContainsKey(name))
            {
                mAllEvents.Add(name, new List<MessageHandler>());
            }

            if (mAllEvents[name].Contains(msgHandler))
            {
                return;
            }

            mAllEvents[name].Add(msgHandler);
        }

        /// <summary>
        /// 移除事件
        /// </summary>
        /// <param name="name"> 事件名 </param>
        /// <param name="msgHandler"> 事件 </param>
        public void RemoveEvent(string name, MessageHandler msgHandler)
        {
            if (!mAllEvents.ContainsKey(name)) return;

            if (!mAllEvents[name].Contains(msgHandler)) return;

            mAllEvents[name].Remove(msgHandler);
        }


        /// <summary>
        /// 清除事件
        /// </summary>
        /// <param name="name"> 事件名 </param>
        public void ClearEvent(string name)
        {
            if (!mAllEvents.ContainsKey(name)) return;

            mAllEvents[name].Clear();
            mAllEvents[name] = null;
        }


        /// <summary>
        /// 清理
        /// </summary>
        public void Clear()
        {
            mAllEvents.Clear();
        }


        internal EventController(string name) : this()
        {
            Name = name;
        }


        private EventController()
        {
            mAllEvents = new Dictionary<string, List<MessageHandler>>();
        }


        private Dictionary<string, List<MessageHandler>> mAllEvents;
    }
}

